//记录日志的函数
const path = require('path')
const moment = require('moment')
const fs = require('fs')
const {
    EOL
} = require('os')

module.exports = (req, resp, next) => {
    let logFilePath = path.join(__dirname, '../', 'logs')
    //拼接日志文件名称
    logFilePath += '/' + moment().format('YYYY-MM-DD') + '.log'
    //内容
    //时间  ip  方式  路径  状态：ok
    let time = moment().format('HH:mm:ss')
    let ip = req.ip
    let method = req.method
    let uri = req.url
    let status = '状态: ok'
    let content = time + ' ' + ip + " " + method + ' ' + uri + ' ' + status
    //判断日志文件路径是否存在
    let bool = fs.existsSync(logFilePath)
    if (bool) {
        //文件存在
        let data = fs.readFileSync(logFilePath, 'utf-8')
        //是否有内容
        if (data) {
            // 有内容，追加
            fs.appendFileSync(logFilePath, EOL + content)
        } else {
            // 无内容，写入
            fs.writeFileSync(logFilePath, content)
        }
    } else {
        //不存在
        fs.writeFileSync(logFilePath, content)
    }
    next()
}